package com.simple.ds.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.google.common.primitives.Longs;
import com.simple.common.entity.constant.Payment;
import com.simple.common.entity.po.TradeEntity;
import com.simple.common.entity.po.sys.Product;
import com.simple.common.entity.po.sys.Trade;
import com.simple.ds.service.MerchantService;
import com.simple.ds.service.ProductService;
import com.simple.ds.service.TradeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author yasud
 * @date 2021年09月19日 13:20
 * @description
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    MerchantService merchantService;

    @Autowired
    TradeService tradeService;

    @Override
    public Product findProductByExpId(Long expId, Long channelId) {
        return null;
    }

    @Override
    public Product chooseProduct(String pCode, Long expId) {
        Product product = buildProduct(pCode);
        return product;
    }

    @Override
    public Product findProductByTrade(Trade trade) {
        TradeEntity tradeEntity = tradeService.getById(trade.getId());
        return buildProduct(tradeEntity.getApiCode());
    }


    @Override
    public Product buildProduct(String code) {
        Product product = new Product();
        product.setId(Longs.fromByteArray(DigestUtil.sha256(code)));
        product.setProductCode(code);

        Payment.PAY_TYPE value = code(code);
        product.setProductCode(value.code);
        product.setName(value.name);
        product.setDescribe(value.name);
        product.setCreateTime(new Date());
        product.setUpdateTime(new Date());
        return product;
    }

    @Override
    public Payment.PAY_TYPE code(String code) {
        for (Payment.PAY_TYPE value : Payment.PAY_TYPE.values()) {
            if (StringUtils.equalsIgnoreCase(value.code, code)) {
                return value;
            }
        }
        throw new RuntimeException("api code无效");
    }


    @Override
    public Payment.PAY_TYPE findCodeByHash(Long hash) {
        for (Payment.PAY_TYPE value : Payment.PAY_TYPE.values()) {
            if (Longs.fromByteArray(DigestUtil.sha256(value.code)) == hash) {
                return value;
            }
        }
        throw new RuntimeException("api code无效");
    }
}
